

//
//  SinaRefreshControl.swift
//  weibo
//
//  Created by sirius on 16/1/8.
//  Copyright © 2016年 sirius. All rights reserved.
//

import UIKit
import SnapKit

class SinaRefreshControl: UIRefreshControl {
 
 //添加一个自定义视图
    override init(){
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
        tintColor = UIColor.clearColor()
        addSubview(refreshView)
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.width.equalTo(160)
            make.height.equalTo(60)
        }
        //添加监听
        addObserver(self, forKeyPath: "frame", options: [], context: nil)
        
    }
    /*
    1.标记一个开关
    */
    var isTurn: Bool = false
    var isLoading: Bool = false
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if refreshing && !isLoading {
            refreshView.pullView.hidden = true
            refreshView.loadingAnimation()
            isLoading = true
        }
        if(object?.frame.origin.y < -50 && !isTurn){
            
            printLog("反过来")
            
            isTurn = true
            refreshView.startTurn()
            
        }else if (object?.frame.origin.y > -50 && isTurn ){
            printLog("返回去")
            
            isTurn  = false
            refreshView.startTurn()
        }
        
    }
    override func endRefreshing(){
        
        super.endRefreshing()
        
        refreshView.removeAnimation()
        refreshView.pullView.hidden = false
        isLoading = false
    }
    deinit{
        removeObserver(self, forKeyPath: "frame")
    }
    
    
    /*
    1. 创建一类继承 UIRefreshControl
    2. 创建视图，创建SinaRefreshView
    3. UIRefreshControl 监听frame的改变
    4. 创建一个翻转动画
    5. 让翻转动画隐藏，显示加载的视图以及动画
    6. 加载完成，恢复
    
    */
    lazy var refreshView: SinaRefreshView = NSBundle.mainBundle().loadNibNamed("SinaRefreshView", owner: nil, options: nil).last as! SinaRefreshView
    
}
